package controllers

import (
	"git.oschina.net/YPTArch/usercenter/models"
	"github.com/devfeel/dotweb"
	"github.com/devfeel/dotweb/framework/crypto"
	"fmt"
	"git.oschina.net/YPTArch/usercenter/libs/data"
	"strings"
	"git.oschina.net/YPTArch/usercenter/remoteserver/rpcremote/securityauthcenter"
	"git.oschina.net/YPTArch/usercenter/libs/regexps"
	"git.oschina.net/YPTArch/usercenter/remoteserver/rpcremote/appcenter"
	"errors"
	"git.oschina.net/YPTArch/basic/sys/logs"
)

//update user pwd
func UpdateUserPwd(ctx dotweb.Context) error {
	result := new(data.Result)
	defer ctx.WriteJson(result)
	userId:=ctx.FormValue("UserId")
	oldPwd:=ctx.FormValue("OldPwd")
	newPwd:=ctx.FormValue("NewPwd")
	if len(strings.TrimSpace(oldPwd))==0{
		result.FailResult("原密码不能为空")
		return nil
	}
	if len(strings.TrimSpace(newPwd))==0{
		result.FailResult("新密码不能为空")
		return nil
	}

	user,err:=models.UserService.GetUserById(userId)
	if err != nil||user==nil {
		result.FailResult("用户不存在")
		return nil
	}

	if user.UserPwd==cryptos.GetMd5String(newPwd){
		result.FailResult("新密码与原密码一致")
		return nil
	}

	if user.UserPwd!=cryptos.GetMd5String(oldPwd){
		result.FailResult("原密码有误")
		return nil
	}

	bag,err:= models.UserService.UpdatePwd(user.UserId,cryptos.GetMd5String(newPwd))
	if err != nil {
		result.ServerErrResult()
		return nil
	}
	if bag {
		err= models.UserService.SetForeUpdatePwd(user.UserId,0)
		if err != nil {
			result.FailResult("修改失败")
		}
		result.SuccessResult("修改成功")
	}else{
		result.FailResult("修改失败")
	}
	return nil
}
//reset user pwd
func ResetUserPwd(ctx dotweb.Context) error {
	result := new(data.Result)
	defer ctx.WriteJson(result)
	userId:=ctx.FormValue("UserId")
	userPwd:="123456"
	if len(strings.TrimSpace(userPwd))==0{
		result.FailResult("密码不能为空")
		return nil
	}
	user,err:=models.UserService.GetUserById(userId)
	if err != nil||user==nil {
		result.FailResult("用户不存在")
		return nil
	}
	bag,err:= models.UserService.UpdatePwd(user.UserId,cryptos.GetMd5String(userPwd))
	if err != nil {
		result.ServerErrResult()
		return nil
	}
	if bag {
		//设置强制修改密码
		err= models.UserService.SetForeUpdatePwd(user.UserId,1)
		if err != nil {
			result.FailResult("重置密码失败")
		}
		result.SuccessResult("重置密码成功")

	}else{
		result.FailResult("重置密码失败")
	}
	return nil
}

func UpdateUserPhone(ctx dotweb.Context) error{
	result:= new(data.Result)
	defer ctx.WriteJson(result)
	userId:=ctx.FormValue("UserId")
	userPhone:=ctx.FormValue("UserPhone")
	if !regexps.ValidatePhone(userPhone){
		result.FailResult("手机格式不正确")
		return nil
	}

	user,err:=models.UserService.GetUserById(userId)
	if err != nil ||user==nil {
		result.FailResult("用户不存在")
		return nil
	}
	if user.UserPhone==userPhone{
		//result.FailResult("新手机号与原手机号一致，不需要修改")
		result.SuccessResult("手机号修改成功")
		return nil
	}
	tag, err := models.UserService.IsExistPhone(userPhone)
	if err != nil {
		result.ServerErrResult()
		return nil
	}
	if tag {
		result.FailResult("手机号已存在")
		return nil
	}
	tag,err= models.UserService.UpdatePhone(userId,userPhone)
	if err != nil {
		result.ServerErrResult()
		return nil
	}
	if tag{
		result.SuccessResult("手机号修改成功")
	}else{
		result.FailResult("手机号修改失败")
	}
	return nil
}
func UpdateUserEmail(ctx dotweb.Context) error {
	result := new(data.Result)
	defer ctx.WriteJson(result)
	userId:=ctx.FormValue("UserId")
	userEmail:=ctx.FormValue("UserEmail")
	if !regexps.ValidateEmail(userEmail){
		result.FailResult("邮箱格式不正确")
		return nil
	}

	user,err:=models.UserService.GetUserById(userId)
	if err != nil ||user==nil {
		result.FailResult("用户不存在")
		return nil
	}
	if user.UserEmail==userEmail{
		//result.FailResult("新电子邮箱与原电子邮箱一致，不需要修改")
		result.SuccessResult("电子邮箱修改成功")
		return nil
	}
	tag, err := models.UserService.IsExistEmail(userEmail)
	if err != nil {
		result.ServerErrResult()
		return nil
	}
	if tag {
		result.FailResult("电子邮箱已存在")
		return nil
	}
	tag,err= models.UserService.UpdateEmail(userId,userEmail)
	if err != nil {
		result.ServerErrResult()
		return nil
	}
	if tag{
		result.SuccessResult("电子邮箱修改成功")
	}else{
		result.FailResult("电子邮箱修改失败")
	}
	return nil
}
func UpdateUserName(ctx dotweb.Context) error  {
	result := new(data.Result)
	defer ctx.WriteJson(result)
	userId:=ctx.FormValue("UserId")
	userName:=ctx.FormValue("UserName")

	user,err:=models.UserService.GetUserById(userId)
	if err != nil ||user==nil {
		result.FailResult("用户不存在")
		return nil
	}
	if user.UserName==userName{
		//result.FailResult("新用户名与原用户名一致，不需要修改")
		result.SuccessResult("用户名修改成功")
		return nil
	}
	tag, err := models.UserService.IsExistName(userName)
	if err != nil {
		result.ServerErrResult()
		return nil
	}
	if tag {
		result.FailResult("用户名已存在")
		return nil
	}
	tag,err= models.UserService.UpdateName(userId,userName)
	if err != nil {
		result.ServerErrResult()
		return nil
	}
	if tag{
		result.SuccessResult("用户名修改成功")
	}else{
		result.FailResult("用户名修改失败")
	}
	return nil
}

func CreateAndAuthorization(ctx dotweb.Context) error  {
	var u = new(models.User)
	result := new(data.Result)
	defer ctx.WriteJson(result)
	ctx.Bind(u)

	appId := ctx.QueryString("client_id")
	if strings.TrimSpace(appId) == "" {
		result.FailResult("invalid_client")
		return nil
	}
	app := appcenter.RemoteGetApp(appId)
	if app == nil {
		result.FailResult("invalid_client")
		return nil
	}
	if strings.TrimSpace(u.UserName) == "" {
		result.FailResult("用户名不能为空")
		return nil
	}
	if strings.TrimSpace(u.UserPhone) == "" {
		result.FailResult("手机号不能为空")
		return nil
	}
	if strings.TrimSpace(u.UserEmail) == "" {
		result.FailResult("Email不能为空")
		return nil
	}
	if strings.TrimSpace(u.UserPwd) == "" {
		result.FailResult("密码不能为空")
		return nil
	}
	if !regexps.ValidatePhone(u.UserPhone){
		result.FailResult("手机格式不正确")
		return nil
	}
	if !regexps.ValidateEmail(u.UserEmail){
		result.FailResult("邮箱格式不正确")
		return nil
	}

	//数据验证
	call := func(v string) (*models.User,error) {
		user,_:= models.UserService.GetUserByLogin(v)
		userAuths,_:= securityauthcenter.GetUserAuthApp(user.UserId)
		for _,userAuth := range userAuths{
			if userAuth.AppId == appId {
				return nil,errors.New("用户已授权")
			}
		}
		//自动授权用户应用权限
		err := securityauthcenter.Create(user.UserId, appId)
		if err != nil {
			logs.Logger.Info(err.Error())
		}
		return user,nil
	}

	tag, err := models.UserService.IsExistName(u.UserName)
	if err != nil {
		result.ServerErrResult()
		return nil
	}
	if tag {
		u,err= call(u.UserName)
		if err != nil {
			logs.Logger.Info(err.Error())
			result.FailResult("用户名已存在")
			return nil
		}
		result.SuccessResult(u)
		return nil
	}
	tag, err = models.UserService.IsExistPhone(u.UserPhone)
	if err != nil {
		result.ServerErrResult()
		return nil
	}
	if tag {
		//当手机号存在时自动授权应用
		u,err= call(u.UserPhone)
		if err != nil {
			logs.Logger.Info(err.Error())
			result.FailResult("手机号已存在")
			return nil
		}
		result.SuccessResult(u)
		return nil
	}
	tag, err = models.UserService.IsExistEmail(u.UserEmail)
	if err != nil {
		result.ServerErrResult()
		return nil
	}
	if tag {
		u,err= call(u.UserEmail)
		if err != nil {
			logs.Logger.Info(err.Error())
			result.FailResult("邮箱已存在")
			return nil
		}
		result.SuccessResult(u)
		return nil
	}
	//生成用户uuid
	u.UserId = cryptos.GetUUID()

	u.UserPwd = cryptos.GetMd5String(u.UserPwd)
	//执行创建用户并授权应用
	res, err := models.UserService.Create(u)
	if err != nil {
		result.ServerErrResult()
		return nil
	}
	if !res {
		result.FailResult("用户注册失败")
		return nil
	}

	//自动授权用户应用权限
	err = securityauthcenter.Create(u.UserId, appId)
	if err != nil {
		fmt.Println(err.Error())
	}
	result.SuccessResult(u)
	return nil
}


func GetUserById(ctx dotweb.Context) error {
	result := new(data.Result)

	userId:=ctx.FormValue("UserId")
	user,err:=models.UserService.GetUserById(userId)
	if err != nil ||user==nil {
		result.FailResult("用户不存在")
		ctx.WriteJson(result)

		return nil
	}
	userView:= new(models.UserView)
	userView.UserId=user.UserId
	userView.UserName=user.UserName
	userView.UserEmail=user.UserEmail
	userView.UserPhone=user.UserPhone
	userView.UserForeUpdatePwd=user.UserForeUpdatePwd
	result.SuccessResult(userView)
	ctx.WriteJson(result)
	return nil
}